import { useParams } from "react-router";
import { useEffect, useState } from "react";
import { useAuth } from "../components/AuthContext.jsx";
import Comments from "../components/Comments.jsx";
import Invite from "../components/Invite.jsx";

export default function EventDetail() {
    const params = useParams();
    const { authInfo } = useAuth();
    const [event, setEvent] = useState(null);

    useEffect(() => {
        getEvent();
    }, []); // 添加依赖，确保 event_id 变化时重新获取

    async function getEvent() {
        try {
            const res = await fetch(`http://127.0.0.1:8000/api/v1/events/${params.event_id}`, {
                headers: {
                    "X-Request-ID": authInfo ? authInfo.token_uuid : "",
                    "Authorization": authInfo ? `Bearer ${authInfo.token}` : "",
                },
            });
            if (res.status === 200) {
                const data = (await res.json()).data;
                console.log(data.event);
                setEvent(data.event);
            } else {
                console.error("Failed to fetch event:", await res.json());
            }
        } catch (error) {
            console.error("Error fetching event:", error);
        }
    }

    async function joinEvent(){
        const res = await fetch(`http://127.0.0.1:8000/api/v1/events/join`,
            {
                method: "post",
                headers: {
                    "X-Request-ID": authInfo ? authInfo.token_uuid : "",
                    "Authorization": authInfo ? `Bearer ${authInfo.token}` : "",
                    "Content-Type": "application/json"
                },
                body: JSON.stringify({"event_id": params.event_id,"user_id": authInfo.user.id})
            });
        if(res.status===201){
            await getEvent()
        }
    }

    return event? (
        <div className="container mx-auto py-8 px-4 sm:px-6 lg:px-8 max-w-4xl">
            {/* Event Details */}
            <div className="bg-white p-6 rounded-lg shadow-md mb-6">
                <h1 className="text-3xl font-bold text-gray-800 mb-2">{event.title}</h1>
                <p className="text-gray-700 mb-4">{event.description}</p>
                <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                    <p className="text-gray-600">
                        Category: <span className="font-semibold">{event.category.name}</span>
                    </p>
                    <p className="text-gray-600">
                        Type: <span className="font-semibold">{event.type}</span>
                    </p>
                    <p className="text-gray-600">
                        Created by: <span className="font-semibold">{event.creator.name} ({event?.creator.email})</span>
                    </p>
                    <p className="text-gray-600">
                        Time: <span className="font-semibold">{event.start_at} - {event.end_at}</span>
                    </p>
                </div>
                {event.can_join && authInfo && (
                    <div className="mt-4 flex flex-col sm:flex-row space-y-2 sm:space-y-0 sm:space-x-4">
                        <button
                            onClick={joinEvent}
                            className="bg-blue-500 text-white px-4 py-2 rounded hover:bg-blue-600">
                            Join
                        </button>
                    </div>
                )}
            </div>

            {/* Creator Section (Admin only) */}
            <div className="bg-white p-6 rounded-lg shadow-md mb-6">
                {authInfo && (
                    <p className="text-lg font-semibold text-gray-800 mb-2">
                        Joined: {event.participants.map(p=>(
                            <span className="ml-2" key={p.email}>{p.email}</span>
                    ))}
                    </p>
                )}
                {/*条件：如果当前登录用户已经加入到此活动*/}
                <button className="bg-blue-500 text-white px-4 py-2 rounded hover:bg-blue-600">Quit</button>

                <Invite getEvent={getEvent} event={event}/>
            </div>

            {/* Comments Section */}
            <Comments event_id={event.id} />
        </div>
    ):<p>Loading...</p>;
}